<template>
    <rx-dialog style="height: 100%;" @handOk="onOk" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form"  :rules="rules" :model="form"  layout="vertical" class="rx-a-form-vertical">
                    <a-form-model-item :label="i18n('listDialog.listSelect','列表选择')" prop="boList" >
                        <rx-input-button    @click="selectBoList" v-model="form.boList" ></rx-input-button>
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('listDialog.dataPermission','数据权限')" >
                        <a-select   v-model="form.pmtAlias" :options="dataAuthAry"
                                  :getPopupContainer="p=>p.parentNode" allowClear />
                    </a-form-model-item>
                    <a-form-item :label="i18n2('form.openMode','打开方式')">
                        <open-mode :local-config="form"></open-mode>
                    </a-form-item>

                    <a-form-model-item :label="i18n('listDialog.columnMap','列映射')">
                        <a-button-group   style="margin-bottom: 6px;">
                            <a-button @click="add()"><i class="iconfont iconadd"></i></a-button>
                            <a-button @click="remove()"><i class="iconfont icontrash"></i></a-button>
                            <a-button @click="moveUp()"><i class="iconfont iconshang"></i></a-button>
                            <a-button @click="moveDown()"><i class="iconfont iconxia"></i></a-button>
                        </a-button-group>

                        <a-table
                            :columns="columns"
                            :dataSource="form.fieldMap"
                            :pagination="false"
                            :bordered="true"
                            :rowSelection="{selectedRowKeys: selectedRowKeys,type:'checkbox', onChange: onSelectChange}"
                            rowKey="idx_"

                        >


                            <template slot="destField" slot-scope="text, record, index"  >
                                <a-select v-model="record.destField" :options="destFields" @change="changeDestField(record)"/>
                            </template>

                            <template slot="srcField" slot-scope="text, record, index"  >
                                <a-select show-search option-filter-prop="children" :filter-option="filterOption"
                                          @focus="fieldFocus(record)" @change="fieldChange($event,record)"
                                          v-model="record.srcField" :options="srcFields"/>
                            </template>

                        </a-table>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
    import {GridMixin, Dialog, Util} from "@lowcode/jpaas-common-lib";
    import FormBoListApi from '@/api/form/core/formBoList';
    import FormBoPermissionApi from "@/api/form/core/formBoPermission";
    import OpenMode from "@/views/modules/form/core/listCommon/OpenMode";
    export default {
        name: "FormBoListConfigOpenListDialog",
        components: {OpenMode},
        props: {
            layerid: {type: String},
            lydata: {type: Object},
            destroy: Function,
            fieldDts:Array,
            conf:Object
        },
        mixins: [GridMixin],
        data() {
            return {
                labelCol1: {span: 6},
                wrapperCol1: {span: 18},
                labelCol: {span: 10},
                wrapperCol: {span: 14},
                idx_: 1,
                form: {
                    boListId: "",
                    name: "",
                    alias: "",
                    boList: "",
                    pmtAlias: "",
                    fieldMap: [],
                    //窗口大小
                    isMax:"YES",
                    height:600,
                    width:800,
                    model:false
                },
                dataAuthAry:[],
                srcFields: [],
                destFields: [],
                selectedRowKeys: [],
                selectedRows: [],
                columns: [
                    {
                        title: this.i18n('listDialog.destField','目标字段'),
                        dataIndex: 'destField',
                        scopedSlots: {customRender: 'destField'},
                    },
                    {
                        title: this.i18n('listDialog.srcField','当前列表字段'),
                        dataIndex: 'srcField',
                        scopedSlots: {customRender: 'srcField'}
                    }
                ],
                rules: {
                    boList: [
                        {required: true, message: this.i18n('listDialog.listRequired','列表必填'), trigger: 'blur'},
                    ],

                },
                curRecord: {}
            }
        },
        created(){
            this.setData(this.conf,this.fieldDts);
        },
        methods: {
            i18n(name,text,key){
                return this.$ti18(name,text,"formBoList",key);
            },
            i18n2(name, text, key) {
                return this.$ti18(name, text, "formBoListDialog", key);
            },
            fieldFocus(record) {
                this.curRecord = record;
            },
            filterOption(input, option) {
                this.curRecord['srcField'] = input;
                this.curRecord['searchField'] = input;
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            fieldChange(value, record) {
                if (record["searchField"] && value != record["searchField"]) {
                    record["srcField"] = record["searchField"];
                }
            },
            validate(callback) {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        callback();
                    }
                });
            },
            getData() {
                // delete this.form.boList;
                var fieldMap = JSON.stringify(this.form.fieldMap);
                this.form.fieldMap = fieldMap;
                return this.form;
            },
            onOk(){
                Util.closeWindow(this,"ok",this.getData());
            },
            cancel(){
                Util.closeWindow(this,"cancel");
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows
            },
            add() {
                this.form.fieldMap.push({
                    destField: "",
                    srcField: "",
                    idx_: this.idx_++
                })
            },
            remove() {
                this.removeRows(this.form.fieldMap, this.selectedRowKeys);
            },
            moveUp() {
                this.toUp(this.form.fieldMap, this.selectedRowKeys)
            },
            moveDown() {
                this.toDown(this.form.fieldMap, this.selectedRowKeys)
            },
            setData(data, fieldDts) {
                this.srcFields = fieldDts;
                if (!data) {
                    return;
                }

                let json=JSON.parse(data);
                json.fieldMap=JSON.parse(json.fieldMap);
                Object.assign(this.form,json);

                var boListId = this.form.boListId;
                if (boListId) {
                    FormBoListApi.get(boListId).then(res => {
                        this.destFields = this.handSearchJson(res.data.searchJson);
                    });
                    this.handDataAuths(this.form.alias);
                }
                if (this.form.fieldMap) {
                    this.form.fieldMap = JSON.parse(data.fieldMap);
                    var idxAry = [];
                    this.form.fieldMap.forEach(item => {
                        idxAry.push(item.idx_);
                    });
                    this.idx_ = Math.max.apply(null, idxAry) + 1;
                }

            },
            handSearchJson(searchJson) {
                var ary = JSON.parse(searchJson);
                var rtn = ary.filter(item => {
                    return item.type == 'income';
                }).map(item => {
                    return {
                        key: item.fieldName,
                        label: item.fieldLabel,
                        fieldOp: item.fieldOp,
                        tablePre: item.tablePre,
                        dataType: item.dataType
                    }
                });
                return rtn;
            },
            changeDestField(record) {
                var destField = record.destField;
                var obj = this.destFields.filter(item => {
                    return item.key == destField;
                })[0];
                Object.assign(record, obj);

            },
            selectBoList() {
                var conf = {
                    curVm: this,
                    data: {
                        single: true
                    },
                    widthHeight: ['1000px', '600px']
                };

                var self_ = this;

                Dialog.openFormBoListDialog(conf, (vm, data) => {
                    var obj = data[0];

                    var jsonObj = {text: obj.name, value: obj.key};
                    var json = JSON.stringify(jsonObj);
                    self_.form.boList = json;
                    self_.form.name = obj.name;
                    self_.form.alias = obj.key;
                    self_.form.boListId = obj.id;

                    self_.handDataAuths(obj.key);
                    self_.destFields = self_.handSearchJson(obj.searchJson);
                })
            },
            handDataAuths(key){
                var self=this;
                FormBoPermissionApi.getListByKey(key).then(res=>{
                    let ary=res.data.list || [];
                    self.dataAuthAry=ary.map(item=>{
                        return {label:item.name,value:item.permissionId};
                    })
                })
            }
        }
    }
</script>

<style scoped>

</style>